package PowerWord.UI.SettingPage;

import PowerWord.UI.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;

public class SoundSettingBar extends Preference implements
		SeekBar.OnSeekBarChangeListener {
	private int mMaxValue = 15;
	private int mValue = 5;

	public SoundSettingBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		setWidgetLayoutResource(R.layout.volume_preference);
	}

	@Override
	protected void onBindView(View view) {
		super.onBindView(view);
		final SeekBar volumnBar = (SeekBar)view.findViewById(R.id.SoundSeekBar);
		volumnBar.setOnSeekBarChangeListener(this);
		volumnBar.setProgress(mValue * 100 / mMaxValue);
	}

	@Override
	protected Object onGetDefaultValue(TypedArray a, int index) {
		return a.getInt(index, 5);
	}

	@Override
	protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
		if (restoreValue) {
			mValue = getPersistedInt(mValue);
		} else {
			int value = (Integer) defaultValue;
			mValue = value;
			persistInt(value);
		}
	}

	@Override
	protected Parcelable onSaveInstanceState() {
		final Parcelable superState = super.onSaveInstanceState();
		if (isPersistent()) {
			return superState;
		}
		// Save the instance state
		final SavedState myState = new SavedState(superState);
		myState.value = mValue;
		return myState;
	}

	@Override
	protected void onRestoreInstanceState(Parcelable state) {
		if (!state.getClass().equals(SavedState.class)) {
			super.onRestoreInstanceState(state);
			return;
		}
		SavedState myState = (SavedState) state;
		super.onRestoreInstanceState(myState.getSuperState());
		mValue = myState.value;
		notifyChanged();
	}

	private static class SavedState extends BaseSavedState {
		int value;

		public SavedState(Parcel source) {
			super(source);
			value = source.readInt();
		}

		@Override
		public void writeToParcel(Parcel dest, int flags) {
			super.writeToParcel(dest, flags);
			dest.writeInt(value);
		}

		public SavedState(Parcelable superState) {
			super(superState);
		}

		public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
			public SavedState createFromParcel(Parcel in) {
				return new SavedState(in);
			}

			public SavedState[] newArray(int size) {
				return new SavedState[size];
			}
		};
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		mValue = progress * mMaxValue / 100;
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		persistInt(mValue);
	}
}
